#include "stdafx.h"
#include "Entity.h"

#include "RenderSystem.h"
#include "SceneManager.h"
#include "ShaderManager.h"

Entity::Entity(void)
{
}


Entity::~Entity(void)
{
}

void Entity::Update(float deltaTime)
{
	mSceneObject->mTransform = DirectX::XMMatrixRotationRollPitchYaw(mRotation.x, mRotation.y, mRotation.z) *
		DirectX::XMMatrixTranslation(mPosition.x, mPosition.y, mPosition.z);

	mSceneObject->mBoundingVolume.mPosition.x = mPosition.x;
	mSceneObject->mBoundingVolume.mPosition.y = mPosition.y;
	mSceneObject->mBoundingVolume.mPosition.z = mPosition.z;
}

void Entity::Init(RenderSystem* render_system, SceneManager* scene_manager, ShaderManager* shader_manager)
{
	mPosition = Vector3(0.0f, 0.0f, 0.0f);
	mRotation = Vector3(0.0f, 0.0f, 0.0f);

	int sizes[]={sizeof(OncePerFrame)};

	Shader* shader = shader_manager->Create("../data/Shaders/vertexshader.hlsl",
		"../data/Shaders/pixelshader.hlsl");
	shader->AllocateVSConstants(1, sizes);

	render_system->CreateConstantBuffers(shader);

	// create input layout
	D3D10_INPUT_ELEMENT_DESC desc[]={
		{"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D10_INPUT_PER_VERTEX_DATA,0},
		{"TEXCOORD",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D10_INPUT_PER_VERTEX_DATA,0},
		{"NORMAL",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D10_INPUT_PER_VERTEX_DATA,0}
	};
	render_system->CreateInputLayout(shader,desc,sizeof(desc)/sizeof(desc[0]));
	
	// create sampler
	Sampler sampler;
	render_system->CreateSamplerState(&sampler,AM_CLAMP,AM_CLAMP,AM_CLAMP,FM_LINEAR,CM_ALWAYS);
	shader->AllocateSamplers(1);
	shader->SetSampler(0,sampler);

	Texture* tex = new Texture;

	// create texture
	render_system->CreateTexture(tex, "../data/Textures/crate.dds");
	
	Renderable* render = new Renderable;

	// create icosahedron
	Vertex vertices[]={
		Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 10.0f, 0.0f), Vector3(10.0f,0.0f,0.0f), Vector3(10.0f,10.0f,0.0f),
		Vector3(0.0f, 0.0f, 10.0f), Vector3(0.0f, 10.0f, 10.0f), Vector3(10.0f,0.0f,10.0f), Vector3(10.0f,10.0f,10.0f)
	};

	struct Indices {
	unsigned short a,b,c;
	};
	Indices indices[]={
		(0.0f, 0.0f, 0.0f), (0.0f, 10.0f, 0.0f), (10.0f,0.0f,0.0f), (10.0f,10.0f,0.0f),
		(0.0f, 0.0f, 10.0f), (0.0f, 10.0f, 10.0f), (10.0f,0.0f,10.0f), (10.0f,10.0f,10.0f)
	};

	
	// create vertex buffer
	render->mCount = sizeof(vertices) / 12;

	render_system->CreateVertexBuffer(&render->mVertexBuffer,BM_DEFAULT,
		render->mCount, sizeof(Vertex), vertices);
	render_system->CreateIndexBuffer(&render->mIndexBuffer, render->mCount,
		sizeof(indices), indices);

	// create depth state
	DepthState* depth = new DepthState;

	render_system->CreateDepthState(depth, false, false);

	mSceneObject = scene_manager->Create(shader, tex, render);
	mSceneObject->mMaterial.mStates.mDepth = depth;
	mSceneObject->mBoundingVolume.mRadius = 12;
}